<?php
abstract class Core_Data_Mappers_Abstract {
	protected $_dbTable;
	protected $_modelclass;
	protected $_businessclass;
	protected $_map;
	
	public function setDbTable($dbTable) {
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw  new Exception('Invalid table data provider');
		}
		$this->_dbTable = $dbTable;
		return  $this;
	}
	
	public function getDbTable() {
		if ( null ===$this->_dbTable) {
			$this->setDbTable($this->_modelclass);
		}
		return $this->_dbTable;
	}
	
	public function map($row) {
		$object = new $this->_businessclass(); 
		foreach ($this->_map as $key=>$value) {
			if(isset($row[$value]))
				$object->$key=$row[$value];
		}
		return $object;
	}
	
	public function reversemap($row) {
		$data = array();
		foreach ($this->_map as $key=>$value) {
			$data[$value]=$row->$key;
		}
		return $data;
	}
	
	public abstract function exists($object);
	protected abstract  function add ($object);
	protected abstract  function edit ($object);
	
	public function save($object) {
		if ($object instanceof $this->_businessclass) {
			if ($this->exists($object)){
				
				$this->edit($object);
			}
			else {
				$this->add($object);
			}
		}
	}
	
	public function fetchAll($where=null,$count=1000,$start=0) {
		$rows = $this->getDbTable()->fetchAll($where,null,$count,$start);
		if (isset($rows) && count($rows)>0) {
			$collection = array();
			foreach ($rows as $item) {
				$collection[] = $this->map($item);
			}
			return $collection;
		}
		return null;	
	}
	
	public function getTableName() {
		return $this->getDbTable()->_name;
	}
	public function fetchQuery(Zend_Db_Table_Select $query) {
		$rows =$this->getDbTable()->fetchAll($query);
		$collection = array();
		if(isset($rows) && count($rows)>0) {
			foreach ($rows as $row) {
				$collection[]=$this->map($row);
			}
		}
		return $collection;
	}
}